package com.ruoyi.system.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.system.domain.ElectricFence;
import com.ruoyi.system.domain.request.alarmrule.BindAlarmRuleParam;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.AlarmRuleFenceMapper;
import com.ruoyi.system.domain.AlarmRuleFence;
import com.ruoyi.system.service.IAlarmRuleFenceService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 告警规则绑定电子围栏的中间Service业务层处理
 * 
 * @author wp
 * @date 2023-08-10
 */
@Service
public class AlarmRuleFenceServiceImpl extends ServiceImpl<AlarmRuleFenceMapper, AlarmRuleFence> implements IAlarmRuleFenceService {

    @Autowired
    private AlarmRuleFenceMapper alarmRuleFenceMapper;

    @DataScope
    @Override
    public List<ElectricFence> selectList(ElectricFence electricFence) {
        return alarmRuleFenceMapper.list(electricFence);
    }

    /**
     * 绑定围栏
     * @param param
     */
    @Transactional
    @Override
    public void bindFence(BindAlarmRuleParam param){
        if (ObjectUtils.isNotEmpty(param.getUnbindIds())){
            //删除原规则栅栏绑定关系
            remove(new QueryWrapper<AlarmRuleFence>()
                    .eq("alarm_rule_id", param.getAlarmRuleId())
                    .in("fence_id", param.getUnbindIds()));
        }
        if (ObjectUtils.isNotEmpty(param.getNewBindIds())){
            //添加现在规则栅栏绑定关系
            List<AlarmRuleFence> alarmRuleFenceList = Arrays.stream(param.getNewBindIds()).map(i ->
                    new AlarmRuleFence().setAlarmRuleId(param.getAlarmRuleId()).setFenceId(i)).collect(Collectors.toList());
            saveBatch(alarmRuleFenceList);
        }
    }
}
